<?php
class Login extends BZ_Controller
{
    public function _init()
    {
        $this->load->helper(array('captcha'));
        $this->load->model('user_model', 'user');
        $this->load->model('user_account_model', 'user_account');
    }

    public function index()
    {
        if (isset($_SERVER['HTTP_REFERER'])) {
            $parseUrl = parse_url($_SERVER['HTTP_REFERER']);
            if (isset($parseUrl['query']) && strpos($parseUrl['query'], 'backurl') !== false) {
                $this->data['backurl'] = urldecode(strstr($parseUrl['query'], 'http'));
            } else {
                $this->data['backurl'] = $_SERVER['HTTP_REFERER'];
            }
        } else {
            $backUrl = get_cookie('backurl');
            $backUrl = $backUrl ? $backUrl : site_url('tourism/tourismprovider/grid');
            delete_cookie('backurl');
            $this->data['backurl'] = $backUrl;
        }
        if (strpos($this->data['backurl'], 'forget')) {
            $this->data['backurl'] = site_url('tourism/tourismprovider/grid');
            $this->data['flag'] = 1; //找回密码跳转过来，默认显示会员登录
        }
        $this->data['captcha'] = $this->getCaptcha(20, 95, 40, 4);
        $this->data['error'] = get_cookie('error');
        $this->load->view('login/login/index', $this->data);
    }

    public function rule()
    {
        $this->load->view('login/login/rule', $this->data);
    }

    //快捷登录
    public function quickLogin()
    {
        $d = $this->input->post();
        $error = get_cookie('error');
        if (!isset($d['mobile_phone']) || !checkMobile($d['mobile_phone'])) {
            $this->ajaxJson(false, '请输入正确的手机号码');
        }
        if (!isset($d['verify']) || strlen($d['verify']) != 6) {
            $this->ajaxJson(false, '请输入正确的手机验证码');
        }
        $endTime = date('Y-m-d H:i:s');
        $result = $this->user_code->findOne(['mobile' => $d['mobile_phone'], 'code' => $d['verify']], 'id, end_time');//, 'end_time' => $endTime
        if ($result->num_rows() <= 0) {
            set_cookie('error', $error + 1, 43200);
            $this->ajaxJson(false, '手机验证码错误');
        }
        if ($result->row(0)->end_time < $endTime) {
            $this->ajaxJson(false, '手机验证码超过有效期，请重新获取~');
        }
        if ($error > 3) {
            if (!isset($d['captcha']) || !$d['captcha']) {
                $this->ajaxJson(false, '请输入右侧验证码', $error);
            }
            if (strtolower($d['captcha']) != strtolower(get_cookie('captcha'))) {
                $this->ajaxJson(false, '右侧验证码错误', $error);
            }
        }
        //获取用户信息
        if (checkMobile($d['mobile_phone'])) {
            $where = ['mobile_phone' => $d['mobile_phone']];
        } else {
            $where = ['user_name' => $d['mobile_phone']];
        }
        /*if (isset($this->provider->site_apart) && $this->provider->site_apart == 1) {//是否独立站点
            $where['provider_id'] = $this->provider->uid;
        }*/
        if (!$res = $this->user->findOne($where)->row()) {
            //注册
            $parent_name = get_cookie('true_user');
            if (!empty($parent_name)) {
                $user = $this->user->findOne(['user_name' => $parent_name], 'uid')->row();
            }
            $d['password'] = mt_rand(100000, 999999);
            $d['provider_id'] = isset($this->provider->uid) ? $this->provider->uid : 0;
            $this->db->trans_begin();
            //注册人增加游币
            $parent_id = !empty($user->uid) ? $user->uid : UTID_BEIZHU;
            $user_id = $this->user->insertUser($d, $parent_id);
            $accountData = ['uid' => $user_id, 'over_beizhu' => 0, 'poundage' => 0, 'bargaining' => 0, 'amount_carry' => 0, 'amount_settlement' => 0, 'amount_bonus' => 0];
            $user_account_id = $this->user_account->insert($accountData);
            if (!$user_id || !$user_account_id || $this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $this->ajaxJson(false, '网络繁忙，请稍候再试');
            }
            $this->db->trans_commit();

            //如果注册成功，则获取数据
            $res = $this->user->findOne(['uid' => $user_id])->row();
        }

        if (intval($res->user_type) & UTID_PROVIDER || intval($res->user_type) & UTID_TELLER) {
            $this->ajaxJson(false, '供应商帐号不可以登录哦');
        }
        if ($res->flag == 2) {
            $this->ajaxJson(false, '该账号已经冻结~');
        }
        //登录成功后处理
        delete_cookie('error');
        $this->user->visitCount($res->uid);
        $userType = $this->usertype($res->user_type);
        $session = array(
            'ACT_UID'      => $res->uid,
            'ACT_UTID'     => $res->user_type,
            'ACT_TYPENAME' => urlencode($userType['type_zh']),
            'ACT_TYPE'     => $userType['type_en'],
            'ACT_EXTRA'    => $res->extra,
            'ALIAS_NAME'   => urlencode($res->alias_name),
            'OWNER_ID'     => $res->uid,
            'OWNER_NAME'   => $res->user_name,
            'PARENT_ID'    => $res->parent_id,
            'PERSONAL_PHOTO'  => urlencode($res->personal_photo),
        );
        set_cookie('frontUser', serialize($session), 3 * 24 * 3600);
        $this->cache->memcached->save('frontUser', serialize($session), 3 * 24 * 3600);
        $url = (($res->user_type & UTID_PROVIDER) || ($res->user_type & UTID_TELLER)) ? $this->config->gongying_url : (!empty($d['backurl']) ? $d['backurl'] : site_url('tourism/tourismprovider/grid'));
        $this->ajaxJson(true, $url);
    }

    //会员登录
    public function normalLogin()
    {
        $d = $this->input->post();
        $error = get_cookie('error');
        if (!isset($d['mobile_phone']) || !$d['mobile_phone']) {
            $this->ajaxJson(false, '请输入账户名');
        }
        if (!isset($d['pw']) || strlen($d['pw']) < 6 || strlen($d['pw']) > 18) {
            $this->ajaxJson(false, '请输入正确的密码');
        }
        if ($error > 3) {
            if (!isset($d['captcha']) || !$d['captcha']) {
                $this->ajaxJson(false, '请输入右侧验证码', $error);
            }
            if (strtolower($d['captcha']) != strtolower(get_cookie('captcha'))) {
                $this->ajaxJson(false, '右侧验证码错误', $error);
            }
        }
        //获取用户信息
        $w = array(
            'pw' => md5($d['pw'])
        );
        if (checkMobile($d['mobile_phone'])) {
            $w['mobile_phone'] = $d['mobile_phone'];
        } else {
            $w['user_name'] = $d['mobile_phone'];
        }
        if (!$res = $this->user->findOne($w)->row()) {
            set_cookie('error', $error + 1, 43200);
            $this->ajaxJson(false, '账号密码错误');
        }
        if (intval($res->user_type) & UTID_PROVIDER || intval($res->user_type) & UTID_TELLER) {
            $this->ajaxJson(false, '供应商帐号不可以登录哦');
        }
        if ($res->flag == 2) {
            $this->ajaxJson(false, '该账号已经冻结');
        }
        //登录成功后处理
        delete_cookie('error');
        $this->user->visitCount($res->uid);
        $userType = $this->usertype($res->user_type);
        $session = array(
            'ACT_UID'      => $res->uid,
            'ACT_UTID'     => $res->user_type,
            'ACT_TYPENAME' => urlencode($userType['type_zh']),
            'ACT_TYPE'     => $userType['type_en'],
            'ACT_EXTRA'    => $res->extra,
            'ALIAS_NAME'   => urlencode($res->alias_name),
            'OWNER_ID'     => $res->uid,
            'OWNER_NAME'   => $res->user_name,
            'PARENT_ID'    => $res->parent_id,
            'PERSONAL_PHOTO'  => urlencode($res->personal_photo),
        );
        $cookie_time = isset($d['remember']) && $d['remember'] == 'on' ?  7 * 24 * 3600 : 3 *24 * 3600;
        set_cookie('frontUser', serialize($session), $cookie_time);
        $this->cache->memcached->save('frontUser', serialize($session), $cookie_time);
        $url = (($res->user_type & UTID_PROVIDER) || ($res->user_type & UTID_TELLER)) ? $this->config->gongying_url : (!empty($d['backurl']) ? $d['backurl'] : site_url('tourism/tourismprovider/grid'));
        $this->ajaxJson(true, $url);
    }
    
    //用户切换直接登陆
    public function userSwitchLogin()
    {
        $uid = $this->input->get('uid');
        $callback = $this->input->get('callback');
        if (!$res = $this->user->findByUid($uid)->row()) {
            $jsonData = json_encode(array(
                'status' => FALSE,
                'msg'    => '账号密码错误'
            ));
            die($callback.'(' . $jsonData . ')');
        }
        if ($res->flag == 2) {
            $jsonData = json_encode(array(
                'status' => FALSE,
                'msg'    => '该账号已经冻结'
            ));
            die($callback.'(' . $jsonData . ')');
        }
        $userType = $this->usertype($res->user_type);
        $session = array(
            'ACT_UID'        => $res->uid,
            'ACT_UTID'       => $res->user_type,
            'ACT_TYPENAME'   => urlencode($userType['type_zh']),
            'ACT_TYPE'       => $userType['type_en'],
            'ACT_EXTRA'      => $res->extra,
            'ALIAS_NAME'     => urlencode($res->alias_name),
            'OWNER_ID'       => $res->uid,
            'OWNER_NAME'     => $res->user_name,
            'PARENT_ID'      => $res->parent_id,
            'PERSONAL_PHOTO' => urlencode($res->personal_photo),
        );
        $cookie_time = 3 *24 * 3600;
        set_cookie('frontUser', serialize($session), $cookie_time);
        $this->cache->memcached->save('frontUser', serialize($session), $cookie_time);
        $url = (($res->user_type & UTID_PROVIDER) || ($res->user_type & UTID_TELLER)) ? $this->config->gongying_url : site_url('tourism/tourismprovider/grid');
        $jsonData = json_encode(array(
            'status' => TRUE,
            'msg'    => $url
        ));
        die($callback.'(' . $jsonData . ')');
    }
    
    //退出登录
    public function logout()
    {
        $from = $this->input->get('from');
        if (get_cookie('frontUser')) {
            delete_cookie('frontUser');
        }
        if (get_cookie('bz_session')) {
            delete_cookie('bz_session');
        }
        $this->cache->memcached->delete('frontUser');
        if ($from == 'userCheck') { //点击切换账户，换个新账号登陆
            $this->redirect(site_url('login/login/index'));
        } else {
            $this->redirect(site_url('login/login/index'));
        }
    }

    public function checkPhone()
    {
        $d = $this->input->post();
        if (!isset($d['mobile_phone']) || !checkMobile($d['mobile_phone'])) {
            $this->ajaxJson(false, '手机号码有误，请检查~');
        }

        return $this->sendCommonSms($d['mobile_phone'], 'SMS_135430024');
    }

    /**
     * 验证码
     */
    public function checkCaptcha()
    {
        $captcha = $this->getCaptcha(20, 95, 40, 4);
        echo json_encode($captcha);exit;
    }
}